package com.lmonkey.servlet.home;

import com.lmonkey.servic.CARTDao;
import com.lmonkey.servic.CATAGORYDao;
import com.lmonkey.servic.COMMENTDao;
import com.lmonkey.servic.PRODUCTDao;
import com.lmonkey.shop.CATEGORY;
import com.lmonkey.shop.COMMENT;
import com.lmonkey.shop.PRODUCT;
import com.lmonkey.shop.USER;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/shangc/selectproductview")
public class SelectProductView extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //菜单
        ArrayList<CATEGORY> flist = CATAGORYDao.selectcat("father");
        request.setAttribute("flist",flist);
        ArrayList<CATEGORY> clist = CATAGORYDao.selectcat("child");
        request.setAttribute("clist",clist);

        //获取参数
        String id  =request.getParameter("id");

        //通过id进行查询评论
        ArrayList<COMMENT> dlist = COMMENTDao.selectAllid(id);
        request.setAttribute("dlist",dlist);

        //获取最近访问
        HttpSession session = request.getSession();
        ArrayList<Integer> ids = (ArrayList<Integer>)session.getAttribute("ids");
        if (ids == null){
            ids = new ArrayList<Integer>();
        }
        //最多5个，如果多次则重第一个开始删
        if (ids.size() >= 5){
            ids.remove(0);
        }
        //添加列表里，但只要一份
        if (id != null && (!ids.contains(Integer.parseInt(id)))){
            ids.add(Integer.parseInt(id));
        }
        session.setAttribute("ids",ids);

        ids = (ArrayList<Integer>)session.getAttribute("ids");

        //从数据库中获取数据
        if (ids != null){
            ArrayList<PRODUCT> lastlist = PRODUCTDao.selectByid1(ids);
             request.setAttribute("lastlist",lastlist);
        }

        PRODUCT p =null;
        if (id != null){
            p = PRODUCTDao.selectByid(Integer.parseInt(id));
            request.setAttribute("p",p);
        }

        //判断用户是否登入
        HttpSession session1 = request.getSession();
        String isLogin = (String)session1.getAttribute("isLogin");
        USER user = (USER)session1.getAttribute("name");
        if (user != null && isLogin.equals("1")){
            String uid = user.getuser_id();
            int count = CARTDao.selectByid(uid);
            request.setAttribute("num",count);
        }

        //获取推荐商品
        if(p != null){
            int cid = p.getProduct_cid();
            ArrayList<PRODUCT> classlist = PRODUCTDao.selectBycid(cid);
            request.setAttribute("classlist",classlist);
        }
        request.getRequestDispatcher("productview.jsp").forward(request,response);
    }
}
